package com.xiaoma.myaudience.biz.activity;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.biz.app.AudienceApplication;
import com.xiaoma.myaudience.biz.model.ActivityDetailInfoModel;
import com.xiaoma.myaudience.biz.model.CaptureModel;
import com.xiaoma.myaudience.biz.model.RankingListModel;
import com.xiaoma.myaudience.biz.task.CaptureTask;
import com.xiaoma.myaudience.biz.task.DataAsyncTask;
import com.xiaoma.myaudience.biz.task.UploadTask;
import com.xiaoma.myaudience.biz.util.Constant;
import com.xiaoma.myaudience.biz.util.UploadUtil.OnUploadProcessListener;
import com.xiaoma.myaudience.util.PicUtils;
import com.xiaoma.myaudience.util.PrefHelper;
import com.xiaoma.myaudience.util.StringUtils;
import com.xiaoma.myaudience.util.activity.BaseActivity;
import com.xiaoma.myaudience.util.model.ModelUtils;
import com.xiaoma.myaudience.biz.util.UploadUtil;

/**
 * 此界面为自拍、活动照片、以及 文字评论共用
 * 
 * @author jpren
 * 
 */
public class CaptureActivity extends BaseActivity implements OnClickListener,OnUploadProcessListener {
	private static final int REQUEST_CODE_CAMERA = 0;
	private static final int REQUEST_CODE_GALLARY = 1;
	private static final String FILE_NAME = "audiemce.jpg";
	private static final int DIALOG_ADD_EVENT_ERROR = 1;
	private static final int DIALOG_TIP = 2;

	private String mImgPath;
	private Uri mPhotoUri;
	private LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
	private double mLocationX;
	private double mLocationY;
	private CaptureTask mCaptureTask;
	private UploadTask mUploadTask;

	private EditText mCaptureContent;
	private Button complete;
	private String mEventId;
	private String mTitle;
	private RatingBar myRatingBar;
	private ProgressDialog mUploadlDialog;
	private String picid;
	private String whatis="1";//标志位 自拍1，图片评论2，文字评论3
private static final String TAG = "uploadImage";
	
	/**
	 * 去上传文件
	 */
	protected static final int TO_UPLOAD_FILE = 1;  
	/**
	 * 上传文件响应
	 */
	protected static final int UPLOAD_FILE_DONE = 2;  //
	/**
	 * 选择文件
	 */
	public static final int TO_SELECT_PHOTO = 3;
	/**
	 * 上传初始化
	 */
	private static final int UPLOAD_INIT_PROCESS = 4;
	/**
	 * 上传中
	 */
	private static final int UPLOAD_IN_PROCESS = 5;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.capture_layout);
		myRatingBar = (RatingBar) findViewById(R.id.rating_bar);
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			mEventId = bundle.getString("eventid");
			mTitle = bundle.getString("title");
		}
		//mEventId = TextUtils.isEmpty(mEventId) ? "173" : mEventId;
		if (TextUtils.isEmpty(mTitle)) {
			setNetEaseTitle(R.string.search_tab);
			myRatingBar.setVisibility(View.GONE);
		} else {
			whatis = "2";
			int length = mTitle.length();
			mTitle = mTitle.substring(0, (length > 10 ? 10 : length));
			setNetEaseTitle(mTitle);
		}
		setNetEaseTitleGravity(Gravity.CENTER);
		setNetEaseTitleBarVisibility(View.VISIBLE);
		setNetEaseTitleIcon(R.drawable.home_title_icon);
		setNetEaseTitleBarExtra(R.layout.video_detail_extra_layout);

		findViewById(R.id.btn_back).setVisibility(View.GONE);
		complete = (Button) findViewById(R.id.show_comments_back_original);
		complete.setText("发送");
		complete.setVisibility(View.VISIBLE);
		complete.setOnClickListener(this);

		mCaptureContent = (EditText) findViewById(R.id.msg_content);

		findViewById(R.id.map_library).setOnClickListener(this);
		findViewById(R.id.camera_btn).setOnClickListener(this);
		findViewById(R.id.camera_img).setOnClickListener(this);
		findViewById(R.id.qq_weibo).setOnClickListener(this);
		findViewById(R.id.sina_weibo).setOnClickListener(this);
		findViewById(R.id.img_del).setOnClickListener(this);
		findViewById(R.id.location).setOnClickListener(this);
		findViewById(R.id.no_log_txt).setOnClickListener(this);
	}

	private void execute() {
		cancel();
		String content = mCaptureContent.getEditableText().toString();
		if(picid==null){
			if(whatis.equals("1")){
				Tips("请先选择或者自拍一张照片");
				return;
			}else{
				 whatis="3";
				 if(TextUtils.isEmpty(content)){
					 Tips("请添加文字评论");
					 return;
				 }
			}
		}else{
			if (TextUtils.isEmpty(mTitle)) {
				whatis="1";
			} else {
				whatis = "2";
			}
		}
		
		mCaptureTask = new CaptureTask(this, DataAsyncTask.TASK_CAPTURE_POST,
				this);
		mCaptureTask.execute(content, String.valueOf(mLocationX), String
				.valueOf(mLocationY), mEventId, PrefHelper.getString(
				CaptureActivity.this, Constant.LOGIN_COOKIE1, ""), PrefHelper
				.getString(CaptureActivity.this, Constant.LOGIN_COOKIE2, ""), 
				((TextView)findViewById(R.id.location)).getText().toString(),
				String.valueOf(myRatingBar.getRating() * 2),picid,whatis);
	}

	private void cancel() {
		if (mCaptureTask != null) {
			mCaptureTask.cancel(true, true);
		}
	}
	
	private void upload() {
		handler.sendEmptyMessage(TO_UPLOAD_FILE);
/*		cancelUpload();
		mUploadTask = new UploadTask(this, DataAsyncTask.TASK_UPLOAD, this);
		Map<String,String> cookie = new HashMap<String,String>();
		cookie.put(Constant.LOGIN_COOKIE1,PrefHelper.getString(CaptureActivity.this, Constant.LOGIN_COOKIE1,""));
		cookie.put(Constant.LOGIN_COOKIE2,PrefHelper.getString(CaptureActivity.this, Constant.LOGIN_COOKIE2,""));
		cookie.put("url", mImgPath);
		mUploadTask.execute(cookie);*/
	}
	
	private String getImg() {
		String uploadBuffer = null;
		 FileInputStream in;
		try {
			in = new FileInputStream(mImgPath);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();  
			byte[] buffer = new byte[1024];  
			int count = 0;  
			while((count = in.read(buffer)) >= 0){  
				baos.write(buffer, 0, count);  
			}  
			uploadBuffer = new String(baos.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
		}  
		return uploadBuffer;
	}
	
	private void cancelUpload() {
		if (mUploadTask != null) {
			mUploadTask.cancel(true, true);
		}
	}

	private void getImgFromGallary() {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(intent, REQUEST_CODE_GALLARY);
	}

	private void getImgFromCamera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		ContentValues values = new ContentValues();
		values.put(MediaStore.Images.Media.TITLE, FILE_NAME);
		mPhotoUri = getContentResolver().insert(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
		startActivityForResult(intent, REQUEST_CODE_CAMERA);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == Activity.RESULT_CANCELED) {
			return;
		}
		switch (requestCode) {
		case REQUEST_CODE_CAMERA:
			mImgPath = StringUtils.getImagePath(CaptureActivity.this, mPhotoUri);
			setImageview(mImgPath);
			break;

		case REQUEST_CODE_GALLARY:
			mImgPath = StringUtils.getImagePath(CaptureActivity.this, data.getData());
			setImageview(mImgPath);
			break;
			
		default:
			break;
		}
		upload();
	}

	private void getLocation() {
		setLocationOption();
		mLocClient = ((AudienceApplication) getApplication()).mLocationClient;
		mLocClient.registerLocationListener(myListener);

		mLocClient.start();
	}

	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setAddrType("all");// 返回的定位结果包含地址信息
		option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
		option.setScanSpan(5000);// 设置发起定位请求的间隔时间为5000ms
		option.disableCache(true);// 禁止启用缓存定位
		option.setPriority(LocationClientOption.NetWorkFirst); // 设置网络优先
		option.setPoiNumber(5); // 最多返回POI个数
		option.setPoiDistance(1000); // poi查询距离
		option.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息
		((AudienceApplication) getApplication()).mLocationClient
				.setLocOption(option);
	}

	private void setImageview(String imgPath) {
		try {
			ImageView imageview = (ImageView) findViewById(R.id.select_image);
			imageview.setImageBitmap(PicUtils.getImageThumbnail(imgPath,
					Constant.CAPTURE_IMG_WIDTH, Constant.CAPTURE_IMG_HEIGHT));
		} catch (Exception e) {

		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.camera_btn:
			getImgFromCamera();
			break;

		case R.id.map_library:
			getImgFromGallary();
			break;

		case R.id.camera_img:
			LinearLayout msgBtn = (LinearLayout) findViewById(R.id.msg_btn);
			msgBtn.setVisibility(msgBtn.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
			RelativeLayout imgContent = (RelativeLayout) findViewById(R.id.img_content);
			imgContent.setVisibility(imgContent.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
			break;
		case R.id.qq_weibo:

			break;
		case R.id.sina_weibo:

			break;
		case R.id.img_del:
			setImageview("");
			break;

		case R.id.show_comments_back_original:
			if (TextUtils.isEmpty(mImgPath) && "173".equals(mEventId)) {
				Tips(R.string.check_img);
				return;
			}
			Boolean islogin = PrefHelper.getBoolean(CaptureActivity.this,
					Constant.LOGIN_ISLOGIN, false);
			if (!islogin) {
				Tips(R.string.capture_no_login);
				return;
			}

			execute();
			break;

		case R.id.location:
			
			if (mLocationX != 0 && mLocationY != 0) {
				Intent intent = new Intent(CaptureActivity.this,
						LocationMapActivity.class);
				intent.putExtra(ActivityDetailInfoModel.PARAM_LOCATION_X,
						mLocationX);
				intent.putExtra(ActivityDetailInfoModel.PARAM_LOCATION_Y,
						mLocationY);
				startActivity(intent);
			} else {
				Tips(R.string.tips_location_no);
			}
			
			break;

		case R.id.no_log_txt:
			Intent intent = new Intent(CaptureActivity.this,
					LoginActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		getLocation();
		findViewById(R.id.no_log).setVisibility(View.GONE);
		findViewById(R.id.capture_all).setVisibility(View.VISIBLE);
		complete.setVisibility(View.VISIBLE);
		Boolean islogin = PrefHelper.getBoolean(CaptureActivity.this,
				Constant.LOGIN_ISLOGIN, false);
		if (!islogin) {
			findViewById(R.id.no_log).setVisibility(View.VISIBLE);
			findViewById(R.id.capture_all).setVisibility(View.GONE);
			complete.setVisibility(View.GONE);
			return;
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		mLocClient.stop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;
			// StringBuffer sb = new StringBuffer(256);
			// sb.append("time : ");
			// sb.append(location.getTime());
			// sb.append("\nerror code : ");
			// sb.append(location.getLocType());
			// sb.append("\nlatitude : ");
			// sb.append(location.getLatitude());
			// sb.append("\nlontitude : ");
			// sb.append(location.getLongitude());
			// sb.append("\nradius : ");
			// sb.append(location.getRadius());
			// if (location.getLocType() == BDLocation.TypeGpsLocation){
			// sb.append("\nspeed : ");
			// sb.append(location.getSpeed());
			// sb.append("\nsatellite : ");
			// sb.append(location.getSatelliteNumber());
			// } else if (location.getLocType() ==
			// BDLocation.TypeNetWorkLocation){
			// // sb.append("\n省：");
			// // sb.append(location.getProvince());
			// // sb.append("\n市：");
			// // sb.append(location.getCity());
			// // sb.append("\n区/县：");
			// // sb.append(location.getDistrict());
			// sb.append("\naddr : ");
			// sb.append(location.getAddrStr());
			// }
			// sb.append("\nsdk version : ");
			// sb.append(mLocClient.getVersion());
			// sb.append("\nisCellChangeFlag : ");
			// sb.append(location.isCellChangeFlag());
			mLocationY = location.getLatitude();
			mLocationX = location.getLongitude();
			((TextView) findViewById(R.id.location)).setText(location
					.getAddrStr());
		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
			StringBuffer sb = new StringBuffer(256);
			sb.append("Poi time : ");
			sb.append(poiLocation.getTime());
			sb.append("\nerror code : ");
			sb.append(poiLocation.getLocType());
			sb.append("\nlatitude : ");
			sb.append(poiLocation.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(poiLocation.getLongitude());
			sb.append("\nradius : ");
			sb.append(poiLocation.getRadius());
			if (poiLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
				sb.append("\naddr : ");
				sb.append(poiLocation.getAddrStr());
			}
			if (poiLocation.hasPoi()) {
				sb.append("\nPoi:");
				sb.append(poiLocation.getPoi());
			} else {
				sb.append("noPoi information");
			}
		}
	}

	@Override
	public void onPostExecute(int what, Object o) {
		super.onPostExecute(what, o);
		switch (what) {
		case DataAsyncTask.TASK_CAPTURE_POST:
			Map<String, Object> map = (Map<String, Object>) o;
			String erroCode = ModelUtils.getStringValue(map,
					CaptureModel.PARAM_CODE);
			if ("0".equals(erroCode)) {
				((EditText) findViewById(R.id.msg_content)).setText("");
				setImageview("");
				
				removeDialog(DIALOG_TIP);
				showDialog(DIALOG_TIP);

			} else if ("-100".equals(erroCode)) {
				String errorMsg = ModelUtils.getStringValue(map,
						CaptureModel.PARAM_ERRORMSG);
				Toast.makeText(CaptureActivity.this, errorMsg,
						Toast.LENGTH_SHORT).show();
			}else if("".equals(erroCode)){
				Toast.makeText(CaptureActivity.this, "发布失败，请重试",
						Toast.LENGTH_SHORT).show();
				setImageview("");
			}
			break;

		default:
			break;
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_ADD_EVENT_ERROR:
			AlertDialog.Builder builder = new Builder(this);
			builder.setMessage(R.string.login_please);
			builder.setCancelable(false);
			builder.setPositiveButton(R.string.confirm,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(CaptureActivity.this,
									LoginActivity.class);
							CaptureActivity.this.startActivity(intent);
						}
					});
			return builder.create();
			
		case DIALOG_TIP: {
			AlertDialog.Builder builde = new Builder(this);
			builde.setCancelable(true);
			builde.setNegativeButton(R.string.add_event_ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface paramDialogInterface, int paramInt) {
							
							Intent intent = new Intent(CaptureActivity.this, ReviewActivity.class);
							intent.putExtra("eventid", mEventId);
							intent.putExtra(ReviewActivity.FROM_ACTIVITY, 1);
							if(whatis.equals("1")){
								intent.putExtra("type", "2");
								intent.putExtra("from", "2");
								intent.putExtra("picid", picid);
							}else if(whatis.equals("2")){
								intent.putExtra("type", "2");
								intent.putExtra("from", "2");
								intent.putExtra("picid", picid);
							}else{
								intent.putExtra("type", "1");
								intent.putExtra("from", "1");
								intent.putExtra("picid", picid);
							}
							//除了自拍都要跳转
							if(!whatis.equals("1")){
								startActivity(intent);
							}
						}
					});
			builde.setMessage("点评成功");
			return builde.create();
		}
		default:
			break;
		}

		return super.onCreateDialog(id);
	}
	
	

	/**
	 * 上传服务器响应回调
	 */
	@Override
	public void onUploadDone(int responseCode, String message) {
		if(null != mUploadlDialog)
			mUploadlDialog.dismiss();
		Message msg = Message.obtain();
		msg.what = UPLOAD_FILE_DONE;
		msg.arg1 = responseCode;
		msg.obj = message;
		handler.sendMessage(msg);
	}
	
	private void toUploadFile()
	{
		//uploadImageResult.setText("正在上传中...");
		if(null == mUploadlDialog){
			mUploadlDialog = new ProgressDialog(this);
			mUploadlDialog.setMessage("正在上传文件...");
			mUploadlDialog.setCancelable(true);
		}
		mUploadlDialog.show();
		String fileKey = "upfile";
		com.xiaoma.myaudience.biz.util.UploadUtil uploadUtil = com.xiaoma.myaudience.biz.util.UploadUtil.getInstance();
		uploadUtil.setOnUploadProcessListener(this);  //设置监听器监听上传状态
		
		Map<String, String> params = new HashMap<String, String>();
		params.put(Constant.LOGIN_COOKIE1,PrefHelper.getString(CaptureActivity.this, Constant.LOGIN_COOKIE1,""));
		params.put(Constant.LOGIN_COOKIE2,PrefHelper.getString(CaptureActivity.this, Constant.LOGIN_COOKIE2,""));
		params.put("type", "pic");
		uploadUtil.uploadFile( mImgPath,fileKey, "http://www.iguanzhong.com/uch/ios/comment.php",params);
	}
	
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case TO_UPLOAD_FILE:
				toUploadFile();
				break;
			
			case UPLOAD_INIT_PROCESS:
				mUploadlDialog.setMax(msg.arg1);
				break;
			case UPLOAD_IN_PROCESS:
				mUploadlDialog.setProgress(msg.arg1);
				
				break;
			case UPLOAD_FILE_DONE:
				
				JSONObject jsonObject = null;
				try {
					jsonObject = new JSONObject(msg.obj.toString());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(jsonObject!=null){
					
				}
				Map<String, Object> returnjson = ModelUtils.json2Map(jsonObject);
        		String rescode = (String) returnjson.get("code");
        		if(rescode.equals("0")){
        			Toast.makeText(CaptureActivity.this,"上传成功", Toast.LENGTH_LONG).show();
        			//获取picid to-do
        				Map<String, String> map = (Map<String, String>) returnjson.get("data");
						picid = map.get("picid");
        		}else{
        			Toast.makeText(CaptureActivity.this,"上传失败，请重试", Toast.LENGTH_LONG).show();
        		}
				String result = "响应码："+msg.arg1+"\n响应信息："+msg.obj+"\n耗时："+UploadUtil.getRequestTime()+"秒";
				//C.setText(result);
				//Toast.makeText(CaptureActivity.this,result, Toast.LENGTH_LONG).show();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
		
	};

	@Override
	public void onUploadProcess(int uploadSize) {
		Message msg = Message.obtain();
		msg.what = UPLOAD_IN_PROCESS;
		msg.arg1 = uploadSize;
		handler.sendMessage(msg );
	}

	@Override
	public void initUpload(int fileSize) {
		Message msg = Message.obtain();
		msg.what = UPLOAD_INIT_PROCESS;
		msg.arg1 = fileSize;
		handler.sendMessage(msg );
	}
}
